<?php
namespace Admin\Controller;
use Think\Controller;

class BackendController extends Controller{
    protected $_name = '';
    protected $_map = array();  //查询条件
    protected $where = "";
    protected $menuid = 0;
    protected $pid = 0;
    protected $result = array();
    protected function _initialize() {
        //parent::_initialize();
        //$this->_name = $this->getActionName();
 
        //$this->check_priv(); //权限
        /* if(!$this->menuid) $this->menuid = I('request.menuid',0,'intval');
        if($this->menuid) {
            $sub_menu = $this->get_menus($this->menuid);
            if($sub_menu['menu']){//默认页面导航选中样式
                foreach($sub_menu['menu'] as $key=>$val) {
                    if((MODULE_NAME == $val['module_name'] && CONTROLLER_NAME == $val['controller_name'] && ACTION_NAME == $val['action_name']) || $val['id'] == $this->pid) {
                        $sub_menu['menu'][$key]['class'] = 'select';
                        break;
                    }
                }
                $this->assign('isget',$this->isget);
            }
            $this->assign('sub_menu', $sub_menu);
        } */
        
        //C('visitor',session('admin'));
        //C('backend',1);
        //$this->assign('visitor',session('admin'));
        //$this->assign('menuid', $this->menuid);
        /* if(C('URL_MODULE_MAP')){
            foreach (C('URL_MODULE_MAP') as $key => $value) {
                if('admin'==$value){
                    C('admin_alias',$key);
                }
            }
        }else{
            C('admin_alias','Admin');
        } */
    }
    
    /**
     * 列表页面
     */
    public function getIndex() {
        $map = $this->_search();//调用本类下面的_search方法生成查询条件
        if(method_exists($this,'_before_search')) {
            $map = $this->_before_search($map);
        }else{
            $this->where && $map = array_merge($map,$this->where);
        }
        //dd($this->where);
        $mod = D($this->_name);
        
        !empty($mod) && $this->_list($mod, $map);
        if(method_exists($this,'_after_search')) {
            $this->_after_search();
        }
        back(1,"", $this->result);
        //$this->display($this->_tpl);
    }
    
    /**
     * 添加
     */
    public function save($valid="") {
        $mod = D($this->_name);
        $pk = $mod->getPk();
        if(IS_GET){
            $form = I("get.");
        }else{
            $form = I("post.");
        }
        //dd($form);
        if($form[$pk]){
            $this->edit($valid);

        }else{
            if($valid){
                $data = $mod->validate($valid)->create($form);
            }else{
                $data = $mod->create($form);
            }
            //dd($data);
            if(false === $data ){
                back(0,$mod->getError());
            }
            if(method_exists($this,'_before_insert')) {
                $data = $this->_before_insert($data);
            }
            $field = $mod->getDbFields();
            
            if($id = $mod->add($data)){
                if(method_exists($this,'_after_insert')){
                    $data[$pk] = $id;
                    $this->_after_insert($id,$data);
                }
            
                back(1, "添加成功" );
            
            }else{
                back(0, "添加失败");
            }
        }
    }
    /**
     * 修改
     */
    public function edit($valid=""){
        $mod = D($this->_name);
        $pk = $mod->getPk();
        if(IS_GET){
            $form = I("get.");
        }else{
            $form = I("post.");
        }
        if (IS_POST) {
            if($valid){
                $data = $mod->validate($valid)->create($form);
            }else{
                $data = $mod->create($form);
            }
            if (false === $data) {
                back(0, $mod->getError());
            }
            if (method_exists($this, '_before_update')) {
                $data = $this->_before_update($data);
            }
            if (false !== $mod->save($data)) {
                if( method_exists($this, '_after_update')){
                    $id = $data['id'];
                    $this->_after_update($id,$data);
                }
                back(1, "修改成功");
            } else {
                back(0, "修改失败");
            }
        } else {
			$id = I('get.'.$pk,0,'intval');
            $info = $mod->find($id);
            if( method_exists($this, '_after_select')){
                if($data = $this->_after_select($info)) $info = $data;
            }
            back(1,"", $info);
        }
    }
    /**
     * ajax修改单个字段值
     */
    public function ajax_edit(){
        //AJAX修改数据
        $mod = D($this->_name);
        $pk = $mod->getPk();
        $id = I('get.'.$pk,0,'intval');
        $field = I('get.field','','trim');
        $val = I('get.val','','trim');
        //允许异步修改的字段列表  放模型里面去 TODO
        $mod->where(array($pk=>$id))->setField($field, $val);
        back(1);
    }
    
    /**
     * 回收
     */
    function trash() {
        $mod = D($this->_name);
        $pk = $mod->getPk();
        $ids = I('request.'.$pk);
        $ids = is_array($ids)?implode(",",$ids):$ids;
        if ($ids) {
            $map[$pk] = array('in',$ids);
            $this->_map && $map = array_merge($map,$this->_map);
            if( method_exists($this, '_before_trash')){
                $after_data = $mod->where($map)->select();
                $this->_before_trash($after_data);
            }
            if (false !== $reg = $mod->where($map)->save(array("deleted"=>1))) {
                if( method_exists($this, '_after_trash')){
                    $this->_after_trash($ids);
                }
                //统一写日志
        
                back(1, "回收成功");
        
            } else {
                back(0, "回收失败");
            }
        } else {
            back(0, '请选择要回收的内容！');
        }
    }
    
    /**
     * 删除
     */
    public function del(){
        $mod = D($this->_name);
        $pk = $mod->getPk();
        $ids = I('get.'.$pk);
        $ids = is_array($ids)?implode(",",$ids):$ids;
 
        if ($ids) {
            $map[$pk] = array('in',$ids);
            $this->_map && $map = array_merge($map,$this->_map);
            if( method_exists($this, '_before_del')){
                $after_data = $mod->where($map)->select();
                $this->_before_del($after_data);
            }
            if (false !== $reg = $mod->where($map)->delete()) {
                if( method_exists($this, '_after_del')){
                    $this->_after_del($ids);
                }
                //统一写日志
                
                back(1, "删除成功");
                
            } else {
                back(0, "删除失败");
            }
        } else {
            back(0, '请选择要删除的内容！');
        }
    }
    /**
     * 获取请求参数生成条件数组
     */
    protected function _search() {
        //生成查询条件
        $mod = D($this->_name);
        $map = array();
        $field = $mod->getDbFields();
        $tablename = $mod->getTableName();
        foreach ($field as $key => $val) {//getDbFields函数用于获得数据表的所有字段名称
            if (substr($key, 0, 1) == '_') {
                continue;//continue方法用于跳出单次循环
            }
            if ('' != I('request.'.$val)) {
                $t = $this->join ? $tablename.'.'.$val : $val;
                $map[$t] = I('request.'.$val);
            }
        }
        /* if($this->apply['Subsite'] && in_array('subsite_id',$field) && C('visitor.subsite')){
            $t = $this->join ? $tablename.'.subsite_id' : 'subsite_id';
            $subsite_id = '' != I('request.subsite_id')?intval(I('request.subsite_id')):array('in',C('visitor.subsite'));
            $map[$t] = $subsite_id;
        } */
        return $map;
    }
    /**
     * 列表处理
     *
     * @param obj $model  实例化后的模型
     * @param array $map  条件数据（默认为空））
     * @param string $order_by  排序（默认为降序）
     * @param string $field_list 显示字段（默认为'*'，全部显示）
     * @param string $union     union查询sql
     * @param string $join     join连表，传入join字句的数组
     * @param intval $pagesize 每页数据行数（默认为40条计录）
     * @param string $custom_fun 自定义方法名称
     */
    protected function _list($model, $map = array(), $order='', $field_list='', $union='', $join=array(),$pagesize_by=10,$custom_fun){
        //排序
 
        $mod_pk = $model->getPk();//getPK函数用于获得实例化对象后的数据表主健的字段名称
        if (I("get.sort")) {
            $sort = I("get.sort");
            if (I("get.order")) {
                $order = I("get.order");
                $order_by = $sort.' '.$order;
            }else{
                $order_by = $sort.' desc';
            }
        }elseif($order){
            $order_by = $order;
        }elseif($this->order){
            $order_by = $this->order;
        }elseif (empty($order_by)){
            $order_by = $mod_pk.' desc';
        }

        if($field_list){
            $field = $field_list;
        }elseif($this->field){
            $field = $this->field;
        }else{
            $field = '*';
        }
        //如果需要分页
        
        if(I('get.pagesize',0,'intval')){
            $pagesize = I('get.pagesize',0,'intval');
        }else if(isset($this->pagesize)){
            $pagesize = $this->pagesize;
        }else{
            $pagesize = $pagesize_by;
        }
         
        if(!$join && $this->join) $join = $this->join;
        if(!is_array($join)) $join = array($join);
        if(!$union && $this->union) $union = $this->union;
        if($this->group) $group = $this->group;
        if ($pagesize) {
            $count = $model->where($map);//获得数据表查询结果的总条数
            if(!empty($join)){
                foreach ($join as $key => $value) {
                    $count = $count->join($value);
                }
            }
            $distinct = $this->distinct ? 'distinct '.$this->distinct : '*';
            if($union){
                $count = $model->query('select count('.$distinct.') as tp_count from('.$count->buildSql().' union all '.$union.') as tp_t');
                $count = $count[0]['tp_count'];
            }else{
                $count = $count->count($distinct);
            }
            //$pager = pager($count, $pagesize);//实例化thinkphp内置的分页显示类

        }
        //var_dump($map);exit;
        $select = $model->field($field)->where($map)->order($order_by);
        if($union){
            $select = $select->union($union,true);
        }
        if(!empty($join)){
            foreach ($join as $key => $value) {
                $select = $select->join($value);
            }
        }
        $this->list_relation && $select->relation(true);

        
        if ($pagesize) {
            $page = I("page",1);
            $page = $page? $page :1;
            $pageStart = ($page-1) * $pagesize;
            $select->limit( $pageStart .','.$pagesize);
            //dd($pageStart .','.$pagesize);
            //$select->limit($pager->firstRow.','.$pager->listRows);
            //$page = $pager->fshow();
            //$this->assign("page", $page);
        }
        $list = $select->group($this->distinct)->select();
        if($custom_fun){
            $fun = $custom_fun;
        }elseif($this->custom_fun){
            $fun = $this->custom_fun;
        }else{
            $fun = '_custom_fun';
        }
        if(method_exists($this,$fun)) {
            $list = $this->$fun($list);
        }

        
        $this->result = array(
            'rows'=>$list,
            'total'=> $count  ?intval($count) :count($list),
            //'pagesize'=>$pagesize,
            //'list_table'=>true
        );
        return $this->result;
    }
   
}